Your First AI application

Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.

In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:

  • Load the image dataset and create a pipeline.
  • Build and Train an image classifier on this dataset.
  • Use your trained model to perform inference on flower images.

We'll lead you through each part which you'll implement in Python.

When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.

Import Resources

In [0]:
# TODO: Make all necessary imports.

import warnings

import time
import numpy as np
import matplotlib.pyplot as plt

import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds

import logging
import json

#config set up
warnings.filterwarnings('ignore')
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
tfds.disable_progress_bar()

#log set up
logger = tf.get_logger()
logger.setLevel(logging.ERROR)

Google Colab Setup

Setting up Google Colab to use google drive for model checkpoint

In [2]:
USE_GOOGLE_COLAB = True

if USE_GOOGLE_COLAB:
  from google.colab import drive
  drive.mount('/content/gdrive')
Drive already mounted at /content/gdrive; to attempt to forcibly remount, call drive.mount("/content/gdrive", force_remount=True).

Load the Dataset

Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.

The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.

In [3]:
!python -m tensorflow_datasets.scripts.download_and_prepare --register_checksums=True --datasets=oxford_flowers102

# TODO: Load the dataset with TensorFlow Datasets.
dataset, dataset_info = tfds.load('oxford_flowers102', split = ['train+test+validation[:20%]', 'train+test+validation[:60%]', 'train+test+validation[:20%]'], as_supervised = True, with_info = True)

# TODO: Create a training set, a validation set and a test set.
#training_set =  dataset['train']
#test_set = dataset['test']
#validation_set = dataset['validation']

training_set, validation_set, test_set = dataset
2020-06-07 23:01:59.724002: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1
I0607 23:02:02.076860 140300146870144 download_and_prepare.py:180] Running download_and_prepare for datasets:
oxford_flowers102
I0607 23:02:02.077586 140300146870144 download_and_prepare.py:181] Version: "None"
I0607 23:02:02.078379 140300146870144 dataset_builder.py:199] Overwrite dataset info from restored data version.
I0607 23:02:02.081491 140300146870144 download_and_prepare.py:130] download_and_prepare for dataset oxford_flowers102/2.0.0...
I0607 23:02:02.081866 140300146870144 dataset_builder.py:285] Reusing dataset oxford_flowers102 (/root/tensorflow_datasets/oxford_flowers102/2.0.0)
name: "oxford_flowers102"
description: "\nThe Oxford Flowers 102 dataset is a consistent of 102 flower categories commonly occurring\nin the United Kingdom. Each class consists of between 40 and 258 images. The images have\nlarge scale, pose and light variations. In addition, there are categories that have large\nvariations within the category and several very similar categories.\n\nThe dataset is divided into a training set, a validation set and a test set.\nThe training set and validation set each consist of 10 images per class (totalling 1020 images each).\nThe test set consists of the remaining 6149 images (minimum 20 per class).\n"
citation: "@InProceedings{Nilsback08,\n   author = \"Nilsback, M-E. and Zisserman, A.\",\n   title = \"Automated Flower Classification over a Large Number of Classes\",\n   booktitle = \"Proceedings of the Indian Conference on Computer Vision, Graphics and Image Processing\",\n   year = \"2008\",\n   month = \"Dec\"\n}\n"
size_in_bytes: 353121411
location {
  urls: "https://www.robots.ox.ac.uk/~vgg/data/flowers/102/"
}
schema {
  feature {
    name: "file_name"
    type: BYTES
  }
  feature {
    name: "image"
    type: INT
    shape {
      dim {
        size: -1
      }
      dim {
        size: -1
      }
      dim {
        size: 3
      }
    }
  }
  feature {
    name: "label"
    type: INT
  }
}
splits {
  name: "test"
  num_shards: 1
  statistics {
    num_examples: 6149
    features {
      name: "file_name"
      type: BYTES
      bytes_stats {
        common_stats {
          num_non_missing: 6149
        }
      }
    }
    features {
      name: "image"
      num_stats {
        common_stats {
          num_non_missing: 6149
        }
        max: 255.0
      }
    }
    features {
      name: "label"
      num_stats {
        common_stats {
          num_non_missing: 6149
        }
        max: 101.0
      }
    }
  }
  shard_lengths: 3074
  shard_lengths: 3075
  num_bytes: 260784877
}
splits {
  name: "train"
  num_shards: 1
  statistics {
    num_examples: 1020
    features {
      name: "file_name"
      type: BYTES
      bytes_stats {
        common_stats {
          num_non_missing: 1020
        }
      }
    }
    features {
      name: "image"
      num_stats {
        common_stats {
          num_non_missing: 1020
        }
        max: 255.0
      }
    }
    features {
      name: "label"
      num_stats {
        common_stats {
          num_non_missing: 1020
        }
        max: 101.0
      }
    }
  }
  shard_lengths: 1020
  num_bytes: 43474584
}
splits {
  name: "validation"
  num_shards: 1
  statistics {
    num_examples: 1020
    features {
      name: "file_name"
      type: BYTES
      bytes_stats {
        common_stats {
          num_non_missing: 1020
        }
      }
    }
    features {
      name: "image"
      num_stats {
        common_stats {
          num_non_missing: 1020
        }
        max: 255.0
      }
    }
    features {
      name: "label"
      num_stats {
        common_stats {
          num_non_missing: 1020
        }
        max: 101.0
      }
    }
  }
  shard_lengths: 1020
  num_bytes: 43180278
}
supervised_keys {
  input: "image"
  output: "label"
}
version: "2.0.0"
download_size: 344878000

Explore the Dataset

In [4]:
dataset_info
Out[4]:
tfds.core.DatasetInfo(
    name='oxford_flowers102',
    version=2.0.0,
    description='
The Oxford Flowers 102 dataset is a consistent of 102 flower categories commonly occurring
in the United Kingdom. Each class consists of between 40 and 258 images. The images have
large scale, pose and light variations. In addition, there are categories that have large
variations within the category and several very similar categories.

The dataset is divided into a training set, a validation set and a test set.
The training set and validation set each consist of 10 images per class (totalling 1020 images each).
The test set consists of the remaining 6149 images (minimum 20 per class).
',
    homepage='https://www.robots.ox.ac.uk/~vgg/data/flowers/102/',
    features=FeaturesDict({
        'file_name': Text(shape=(), dtype=tf.string),
        'image': Image(shape=(None, None, 3), dtype=tf.uint8),
        'label': ClassLabel(shape=(), dtype=tf.int64, num_classes=102),
    }),
    total_num_examples=8189,
    splits={
        'test': 6149,
        'train': 1020,
        'validation': 1020,
    },
    supervised_keys=('image', 'label'),
    citation="""@InProceedings{Nilsback08,
       author = "Nilsback, M-E. and Zisserman, A.",
       title = "Automated Flower Classification over a Large Number of Classes",
       booktitle = "Proceedings of the Indian Conference on Computer Vision, Graphics and Image Processing",
       year = "2008",
       month = "Dec"
    }""",
    redistribution_info=,
)
In [5]:
# TODO: Get the number of examples in each set from the dataset info.
num_examples_train = dataset_info.splits['train'].num_examples
num_examples_test = dataset_info.splits['test'].num_examples
num_examples_validation = dataset_info.splits['validation'].num_examples

print('There are {:,} examples in train set'.format(num_examples_train) + '\n')
print('There are {:,} examples in test set'.format(num_examples_test) + '\n')
print('There are {:,} examples in validation set'.format(num_examples_validation) + '\n')

# TODO: Get the number of classes in the dataset from the dataset info.
num_classes = dataset_info.features['label'].num_classes

print('There are {:,} classes in train set'.format(num_classes) + '\n')
There are 1,020 examples in train set

There are 6,149 examples in test set

There are 1,020 examples in validation set

There are 102 classes in train set

In [0]:
#swapping test set and train set since test set has more data
temp = training_set
training_set = test_set
test_set = temp
In [7]:
# TODO: Print the shape and corresponding label of 3 images in the training set.

for image, label in training_set.take(3):
    print('\u2022 The images in the training set has shape:', image.shape ,' and has {} label'.format(label),'\n')
• The images in the training set has shape: (500, 667, 3)  and has 72 label 

• The images in the training set has shape: (500, 666, 3)  and has 84 label 

• The images in the training set has shape: (670, 500, 3)  and has 70 label 

In [8]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding image label. 

for image, label in training_set.take(1):
    image = image.numpy()
    label = label.numpy()

plt.imshow(image)
plt.title(label=label)

plt.show()

Label Mapping

You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.

In [0]:
#with open('label_map.json', 'r') as f:
#modify for google colab

if USE_GOOGLE_COLAB:
  with open("/content/gdrive/My Drive/Intro_To_MachineLearning_Image_classifier/label_map.json" , 'r' ) as f:
    class_names = json.load(f)
else:
  with open('label_map.json', 'r') as f:
    class_names = json.load(f)
In [10]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding class name. 

for image, label in training_set.take(1):
  image = image.numpy()
  label = label.numpy()

plt.imshow(image)
plt.title(class_names[str(label)])

plt.show()

Create Pipeline

In [0]:
# TODO: Create a pipeline for each set.
BATCH_SIZE = 100
IMAGE_SIZE = 224

def format_image(image, label):
  image = tf.cast(image, tf.float32)
  image = tf.image.resize(image , (IMAGE_SIZE, IMAGE_SIZE))
  image /= 255
  return image, label

training_batches = training_set.shuffle(num_examples_train//4).map(format_image).batch(BATCH_SIZE).prefetch(1)
validation_batches = validation_set.map(format_image).batch(BATCH_SIZE).prefetch(1)
testing_batches = test_set.map(format_image).batch(BATCH_SIZE).prefetch(1)

Build and Train the Classifier

Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.

We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!

Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:

  • Load the MobileNet pre-trained network from TensorFlow Hub.
  • Define a new, untrained feed-forward network as a classifier.
  • Train the classifier.
  • Plot the loss and accuracy values achieved during training for the training and validation set.
  • Save your trained model as a Keras model.

We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!

When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.

Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.

In [0]:
# TODO: Build and train your network.
# * Load the MobileNet pre-trained network from TensorFlow Hub.
# * Define a new, untrained feed-forward network as a classifier.
# * Train the classifier.
# * Plot the loss and accuracy values achieved during training for the training and validation set.
# * Save your trained model as a Keras model.
In [0]:
# Load the MobileNet pre-trained network from TensorFlow Hub

URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"

mobilenet_model = hub.KerasLayer(URL, input_shape=(IMAGE_SIZE, IMAGE_SIZE,3))
In [0]:
# Freeze weights for the transfer network

mobilenet_model.trainable = False
In [14]:
# Define a new, untrained feed-forward network as a classifier
NEURONS = [1024,512,256]

DROP_RATE = 0.3

model = tf.keras.Sequential(mobilenet_model)

for neurons in NEURONS:
    model.add(tf.keras.layers.Dropout(DROP_RATE))
    model.add(tf.keras.layers.Dense(neurons, activation = 'relu'))

model.add(tf.keras.layers.Dropout(DROP_RATE))
model.add(tf.keras.layers.Dense(num_classes, activation = 'softmax'))

early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)

model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 1280)              2257984   
_________________________________________________________________
dropout (Dropout)            (None, 1280)              0         
_________________________________________________________________
dense (Dense)                (None, 1024)              1311744   
_________________________________________________________________
dropout_1 (Dropout)          (None, 1024)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 512)               524800    
_________________________________________________________________
dropout_2 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 256)               131328    
_________________________________________________________________
dropout_3 (Dropout)          (None, 256)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 102)               26214     
=================================================================
Total params: 4,252,070
Trainable params: 1,994,086
Non-trainable params: 2,257,984
_________________________________________________________________
In [15]:
# Train the classifier

model.compile(optimizer = 'adam',
                        loss = 'sparse_categorical_crossentropy',
                        metrics = ['accuracy'])


EPOCHS = 100

train_history = model.fit(training_batches,
                    epochs = EPOCHS,
                    validation_data = validation_batches,
                    callbacks = [early_stopping])
Epoch 1/100
74/74 [==============================] - 58s 780ms/step - loss: 3.5901 - accuracy: 0.2063 - val_loss: 1.8058 - val_accuracy: 0.5497
Epoch 2/100
74/74 [==============================] - 55s 750ms/step - loss: 1.9223 - accuracy: 0.4995 - val_loss: 0.8706 - val_accuracy: 0.7678
Epoch 3/100
74/74 [==============================] - 56s 758ms/step - loss: 1.2859 - accuracy: 0.6491 - val_loss: 0.5531 - val_accuracy: 0.8543
Epoch 4/100
74/74 [==============================] - 57s 776ms/step - loss: 0.9696 - accuracy: 0.7317 - val_loss: 0.4011 - val_accuracy: 0.8899
Epoch 5/100
74/74 [==============================] - 55s 749ms/step - loss: 0.7864 - accuracy: 0.7788 - val_loss: 0.3055 - val_accuracy: 0.9185
Epoch 6/100
74/74 [==============================] - 56s 752ms/step - loss: 0.6755 - accuracy: 0.8010 - val_loss: 0.2541 - val_accuracy: 0.9298
Epoch 7/100
74/74 [==============================] - 56s 761ms/step - loss: 0.5663 - accuracy: 0.8364 - val_loss: 0.1810 - val_accuracy: 0.9533
Epoch 8/100
74/74 [==============================] - 56s 750ms/step - loss: 0.5130 - accuracy: 0.8499 - val_loss: 0.1548 - val_accuracy: 0.9593
Epoch 9/100
74/74 [==============================] - 56s 753ms/step - loss: 0.4442 - accuracy: 0.8680 - val_loss: 0.1179 - val_accuracy: 0.9676
Epoch 10/100
74/74 [==============================] - 56s 762ms/step - loss: 0.4023 - accuracy: 0.8821 - val_loss: 0.1136 - val_accuracy: 0.9710
Epoch 11/100
74/74 [==============================] - 55s 750ms/step - loss: 0.3634 - accuracy: 0.8935 - val_loss: 0.0961 - val_accuracy: 0.9744
Epoch 12/100
74/74 [==============================] - 55s 746ms/step - loss: 0.3284 - accuracy: 0.9000 - val_loss: 0.0772 - val_accuracy: 0.9818
Epoch 13/100
74/74 [==============================] - 57s 766ms/step - loss: 0.3109 - accuracy: 0.9059 - val_loss: 0.0653 - val_accuracy: 0.9862
Epoch 14/100
74/74 [==============================] - 56s 751ms/step - loss: 0.2923 - accuracy: 0.9103 - val_loss: 0.0581 - val_accuracy: 0.9857
Epoch 15/100
74/74 [==============================] - 55s 737ms/step - loss: 0.2699 - accuracy: 0.9227 - val_loss: 0.0508 - val_accuracy: 0.9878
Epoch 16/100
74/74 [==============================] - 56s 762ms/step - loss: 0.2257 - accuracy: 0.9297 - val_loss: 0.0500 - val_accuracy: 0.9870
Epoch 17/100
74/74 [==============================] - 55s 746ms/step - loss: 0.2426 - accuracy: 0.9246 - val_loss: 0.0505 - val_accuracy: 0.9871
Epoch 18/100
74/74 [==============================] - 55s 744ms/step - loss: 0.2213 - accuracy: 0.9350 - val_loss: 0.0414 - val_accuracy: 0.9896
Epoch 19/100
74/74 [==============================] - 56s 760ms/step - loss: 0.2100 - accuracy: 0.9369 - val_loss: 0.0377 - val_accuracy: 0.9906
Epoch 20/100
74/74 [==============================] - 56s 762ms/step - loss: 0.2009 - accuracy: 0.9390 - val_loss: 0.0346 - val_accuracy: 0.9918
Epoch 21/100
74/74 [==============================] - 56s 750ms/step - loss: 0.1810 - accuracy: 0.9470 - val_loss: 0.0318 - val_accuracy: 0.9922
Epoch 22/100
74/74 [==============================] - 56s 758ms/step - loss: 0.1909 - accuracy: 0.9430 - val_loss: 0.0230 - val_accuracy: 0.9952
Epoch 23/100
74/74 [==============================] - 56s 757ms/step - loss: 0.1866 - accuracy: 0.9426 - val_loss: 0.0416 - val_accuracy: 0.9897
Epoch 24/100
74/74 [==============================] - 55s 745ms/step - loss: 0.1753 - accuracy: 0.9463 - val_loss: 0.0271 - val_accuracy: 0.9942
Epoch 25/100
74/74 [==============================] - 56s 761ms/step - loss: 0.1694 - accuracy: 0.9445 - val_loss: 0.0259 - val_accuracy: 0.9933
Epoch 26/100
74/74 [==============================] - 55s 744ms/step - loss: 0.1585 - accuracy: 0.9527 - val_loss: 0.0229 - val_accuracy: 0.9943
Epoch 27/100
74/74 [==============================] - 55s 749ms/step - loss: 0.1449 - accuracy: 0.9558 - val_loss: 0.0211 - val_accuracy: 0.9946
Epoch 28/100
74/74 [==============================] - 57s 767ms/step - loss: 0.1432 - accuracy: 0.9581 - val_loss: 0.0256 - val_accuracy: 0.9937
Epoch 29/100
74/74 [==============================] - 55s 744ms/step - loss: 0.1352 - accuracy: 0.9605 - val_loss: 0.0244 - val_accuracy: 0.9933
Epoch 30/100
74/74 [==============================] - 55s 749ms/step - loss: 0.1345 - accuracy: 0.9593 - val_loss: 0.0185 - val_accuracy: 0.9961
Epoch 31/100
74/74 [==============================] - 57s 766ms/step - loss: 0.1355 - accuracy: 0.9585 - val_loss: 0.0224 - val_accuracy: 0.9941
Epoch 32/100
74/74 [==============================] - 55s 745ms/step - loss: 0.1326 - accuracy: 0.9574 - val_loss: 0.0238 - val_accuracy: 0.9931
Epoch 33/100
74/74 [==============================] - 55s 743ms/step - loss: 0.1445 - accuracy: 0.9608 - val_loss: 0.0222 - val_accuracy: 0.9940
Epoch 34/100
74/74 [==============================] - 56s 760ms/step - loss: 0.1312 - accuracy: 0.9599 - val_loss: 0.0155 - val_accuracy: 0.9967
Epoch 35/100
74/74 [==============================] - 56s 750ms/step - loss: 0.1270 - accuracy: 0.9623 - val_loss: 0.0194 - val_accuracy: 0.9960
Epoch 36/100
74/74 [==============================] - 55s 746ms/step - loss: 0.1101 - accuracy: 0.9661 - val_loss: 0.0206 - val_accuracy: 0.9946
Epoch 37/100
74/74 [==============================] - 56s 762ms/step - loss: 0.1108 - accuracy: 0.9660 - val_loss: 0.0187 - val_accuracy: 0.9949
Epoch 38/100
74/74 [==============================] - 56s 761ms/step - loss: 0.1253 - accuracy: 0.9608 - val_loss: 0.0184 - val_accuracy: 0.9952
Epoch 39/100
74/74 [==============================] - 56s 755ms/step - loss: 0.1121 - accuracy: 0.9665 - val_loss: 0.0224 - val_accuracy: 0.9937
In [16]:
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.

training_accuracy = train_history.history['accuracy']
validation_accuracy = train_history.history['val_accuracy']

training_loss = train_history.history['loss']
validation_loss = train_history.history['val_loss']

epochs_range=range(len(training_accuracy))

plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, training_accuracy, label='Training Accuracy')
plt.plot(epochs_range, validation_accuracy, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, training_loss, label='Training Loss')
plt.plot(epochs_range, validation_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

Testing your Network

It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.

In [17]:
# TODO: Print the loss and accuracy values achieved on the entire test set.

for image_batch, label_batch in testing_batches.take(4):
    ps = model.predict(image_batch)
    images = image_batch.numpy().squeeze()
    labels = label_batch.numpy()

plt.figure(figsize=(10,15))

for n in range(30):
    plt.subplot(6,5,n+1)
    plt.imshow(images[n], cmap = plt.cm.binary)
    color = 'green' if np.argmax(ps[n]) == labels[n] else 'red'
    plt.title(class_names[str(np.argmax(ps[n]))] , color=color)
    plt.axis('off')

Save the Model

Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).

In [19]:
# TODO: Save your trained model as a Keras model.

t = time.time()
if USE_GOOGLE_COLAB :
  save_path = '/content/gdrive/My Drive/Intro_To_MachineLearning_Image_classifier/Image_Classifier_{}.h5'
else:
  save_path = './Image_Classifier_{}.h5'

saved_keras_model_filepath = save_path.format(int(t))

model.save(saved_keras_model_filepath)
print(model)
<tensorflow.python.keras.engine.sequential.Sequential object at 0x7f4dc38966d8>

Load the Keras Model

Load the Keras model you saved above.

In [20]:
# TODO: Load the Keras model
print(saved_keras_model_filepath)

reloaded_model = tf.keras.models.load_model((saved_keras_model_filepath),custom_objects={'KerasLayer':hub.KerasLayer})

reloaded_model.summary()
/content/gdrive/My Drive/Intro_To_MachineLearning_Image_classifier/Image_Classifier_1591573355.h5
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 1280)              2257984   
_________________________________________________________________
dropout (Dropout)            (None, 1280)              0         
_________________________________________________________________
dense (Dense)                (None, 1024)              1311744   
_________________________________________________________________
dropout_1 (Dropout)          (None, 1024)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 512)               524800    
_________________________________________________________________
dropout_2 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 256)               131328    
_________________________________________________________________
dropout_3 (Dropout)          (None, 256)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 102)               26214     
=================================================================
Total params: 4,252,070
Trainable params: 1,994,086
Non-trainable params: 2,257,984
_________________________________________________________________

Inference for Classification

Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.

Image Pre-processing

The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).

First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.

Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.

Finally, convert your image back to a NumPy array using the .numpy() method.

In [0]:
# TODO: Create the process_image function

def process_image(image):
  image = tf.convert_to_tensor(image)
  image = tf.cast(image, tf.float32)
  image = tf.image.resize(image , (IMAGE_SIZE, IMAGE_SIZE))
  image /= 255
  return image 

To check your process_image function we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.

In [22]:
from PIL import Image

if USE_GOOGLE_COLAB:
  image_path = '/content/gdrive/My Drive/Intro_To_MachineLearning_Image_classifier/test_images/hard-leaved_pocket_orchid.jpg'
else:
  image_path = './test_images/hard-leaved_pocket_orchid.jpg'


im = Image.open(image_path)
test_image = np.asarray(im)

processed_test_image = process_image(test_image)

fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()

Once you can get images in the correct format, it's time to write the predict function for making inference with your model.

Inference

Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.

In [23]:
# TODO: Create the predict function

def predict(image_path, model, top_k):
  im = Image.open(image_path)
  im = np.asarray(im)
  im = process_image(im)
  im = tf.convert_to_tensor(im)
  im = tf.reshape(im, (1, IMAGE_SIZE, IMAGE_SIZE, 3))
  probabilities = model.predict(im)
  temp = zip(probabilities.squeeze(), list(range(1,num_classes+1)))
  sorted_temp = sorted(temp, key = lambda tmp: tmp[0], reverse=True) 
  return list(zip(*sorted_temp[:top_k]))

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
(1.0, 3.523547e-11, 9.1538e-14, 4.6105782e-14, 1.8213212e-14)
(2, 7, 69, 20, 94)

Sanity Check

It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.

In [24]:
# TODO: Plot the input image along with the top 5 classes

if USE_GOOGLE_COLAB:
  image_path = '/content/gdrive/My Drive/Intro_To_MachineLearning_Image_classifier/test_images/*.jpg'
else:
  image_path = './test_images/*.jpg'

import glob
file_path = glob.glob(image_path)

for img in file_path:
  probs, classes = predict(img, model, 5)
  class_name = list()
  for i in classes:
    class_name.append(class_names[str(i)])
  
  fig, (ax1, ax2) = plt.subplots(figsize=(16,8), ncols=2)
  ax1.imshow(np.asarray(Image.open(img)))
  ax1.axis('off')

  ax2.barh(range(5), probs)
  ax2.set_yticks(np.arange(5))
  ax2.set_yticklabels(class_name)
  ax2.set_title('Class Probability')
  ax2.set_xlim(0, 1.1)
  plt.tight_layout()